import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { UserInfo, LoginForm } from '@/types/user'
import { login, logout, getUserInfo } from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router from '@/router'

export const useUserStore = defineStore(
  'user',
  () => {
    // 状态
    const token = ref(getToken())
    const userInfo = ref<UserInfo | null>(null)
    const permissions = ref<string[]>([])
    const roles = ref<string[]>([])

    // 计算属性
    const isLogin = computed(() => !!token.value)
    const userName = computed(() => userInfo.value?.userName || '')
    const avatar = computed(() => userInfo.value?.avatar || '')
    const nickName = computed(() => userInfo.value?.nickName || '')

    // 用户登录
    const loginAction = async (loginForm: LoginForm) => {
      try {
        const response = await login(loginForm)
        const { token: accessToken } = response.data // 匹配后端SysLoginController返回的token字段
        
        // 保存token
        token.value = accessToken
        setToken(accessToken)
        
        // 获取用户信息
        await getUserInfoAction()
        
        return Promise.resolve(response.data)
      } catch (error) {
        return Promise.reject(error)
      }
    }

    // 获取用户信息
    const getUserInfoAction = async () => {
      try {
        const { data } = await getUserInfo()
        
        userInfo.value = data.user
        permissions.value = data.permissions || []
        roles.value = data.roles || []
        
        return Promise.resolve(data)
      } catch (error) {
        return Promise.reject(error)
      }
    }

    // 用户登出
    const logoutAction = async () => {
      try {
        await logout()
      } catch (error) {
        console.error('登出接口调用失败:', error)
      } finally {
        // 清除本地数据
        resetUserInfo()
        
        // 跳转到登录页
        router.push('/login')
      }
    }

    // 重置用户信息
    const resetUserInfo = () => {
      token.value = ''
      userInfo.value = null
      permissions.value = []
      roles.value = []
      removeToken()
    }

    // 检查权限
    const hasPermission = (permission: string | string[]): boolean => {
      if (!permission) return true
      
      if (typeof permission === 'string') {
        return permissions.value.includes(permission)
      }
      
      if (Array.isArray(permission)) {
        return permission.some(p => permissions.value.includes(p))
      }
      
      return false
    }

    // 检查角色
    const hasRole = (role: string | string[]): boolean => {
      if (!role) return true
      
      if (typeof role === 'string') {
        return roles.value.includes(role)
      }
      
      if (Array.isArray(role)) {
        return role.some(r => roles.value.includes(r))
      }
      
      return false
    }

    return {
      // 状态
      token,
      userInfo,
      permissions,
      roles,
      
      // 计算属性
      isLogin,
      userName,
      avatar,
      nickName,
      
      // 方法
      loginAction,
      getUserInfoAction,
      logoutAction,
      resetUserInfo,
      hasPermission,
      hasRole,
    }
  },
  {
    persist: {
      key: 'kexilo-user',
      storage: localStorage,
      paths: ['token', 'userInfo'],
    },
  }
)
